package com.example.taobaounion3.presenter.impl;

import android.webkit.URLUtil;

import com.example.taobaounion3.model.Api;
import com.example.taobaounion3.model.domain.HomePagerContent;
import com.example.taobaounion3.presenter.ICategoryPagerPresenter;
import com.example.taobaounion3.utils.LogUtils;
import com.example.taobaounion3.utils.RetrofitManager;
import com.example.taobaounion3.utils.urlUtils;
import com.example.taobaounion3.view.ICategoryPagerCallback;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Url;

public class CategoryPagePresenterlmpl implements ICategoryPagerPresenter {

    private Map<Integer,Integer> pagesInfo=new HashMap<>();

    private List<ICategoryPagerCallback> callbacks=new ArrayList<>();

    private Integer mCurrentPage;

    public static final int DEFALT_PAGE=1;



//    private static ICategoryPagerPresenter sInstance=null;
//
//    public static ICategoryPagerPresenter getInstance(){
//        if (sInstance==null){
//            sInstance=new CategoryPagePresenterlmpl();
//        }
//        return sInstance;
//    }
    //根据分类id加载内容
    @Override
    public void getCaontentByCategoryId(int categoryId) {
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId()==categoryId) {
                callback.onLoading();
            }

        }
       
        Integer targetPage=pagesInfo.get(categoryId);
        if (targetPage==null){
            targetPage=DEFALT_PAGE;
            pagesInfo.put(categoryId,targetPage);
        }
        Call<HomePagerContent> task = createTask(categoryId, targetPage);
        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(Call<HomePagerContent> call, Response<HomePagerContent> response) {
                int code =response.code();
                LogUtils.d(CategoryPagePresenterlmpl.this,"code-->"+code);
                if (code== HttpURLConnection.HTTP_OK){
                    HomePagerContent pagerContent=response.body();
                    //LogUtils.d(CategoryPagePresenterlmpl.this,"pageContent-->"+pagerContent);
                    //把数据给到UI更新
                    handleHomePageContentResult(pagerContent,categoryId);
                }
                else {
                    handleNetworkError(categoryId);
                }
            }

            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                LogUtils.d(this,"onFailure-->"+t.toString());
                handleNetworkError(categoryId);
            }
        });
    }

    private Call<HomePagerContent> createTask(int categoryId, Integer targetPage) {
        String homePagerUrl= urlUtils.createHomePagerUrl(categoryId,targetPage);
        //LogUtils.d(CategoryPagePresenterlmpl.this,"home pager url -->"+homePagerUrl);
        Retrofit retrofit= RetrofitManager.getOurInstance().getRetrofit();
        Api api=retrofit.create(Api.class);
        return api.getHomePagerContent(homePagerUrl);
    }

    private void handleNetworkError(int categoryId) {
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId()==categoryId) {
                callback.onError();
            }

        }
    }

    private void handleHomePageContentResult(HomePagerContent pageContent, int categoryId) {
        //通知UI层更新数据
        List<HomePagerContent.DataBean> data=pageContent.getData();
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId()==categoryId) {
                if (pageContent==null||pageContent.getData().size()==0){
                    callback.onLoaderMoreEmpty();
                }
                else {
                    List<HomePagerContent.DataBean> looperData=data.subList(data.size()-5,data.size());
                    callback.onLooperListLoaded(looperData);
                    callback.onContentLoaded(data);
                }
            }


        }
    }

    @Override
    public void loaderMore(int categoryId) {
        //加载更多内容的数据
        //1.拿到当前页码
        mCurrentPage =pagesInfo.get(categoryId);
        if (mCurrentPage==null){
            mCurrentPage=1;
        }
        //2.页码++
        mCurrentPage++;
        //3.加载数据
        Call<HomePagerContent> task = createTask(categoryId, mCurrentPage);
        //4.处理数据结果
        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(Call<HomePagerContent> call, Response<HomePagerContent> response) {
                //结果
                int code =response.code();
                LogUtils.d(CategoryPagePresenterlmpl.this,"result code-->"+code);
                if (code== HttpURLConnection.HTTP_OK) {
                    HomePagerContent result=response.body();
                    LogUtils.d(CategoryPagePresenterlmpl.this,"result-->"+result.toString());
                    handleLoaderResult(result,categoryId);
                }else{
                    handleLoaderMoreError(categoryId);
                }
            }

            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                //请求失败
                LogUtils.d(CategoryPagePresenterlmpl.this,t.toString());
                handleLoaderMoreError(categoryId);
            }
        });
    }

    private void handleLoaderResult(HomePagerContent result, int categoryId) {
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId()==categoryId) {
                if (result==null||result.getData().size()==0) {
                    callback.onLoaderMoreEmpty();
                }else {
                    callback.onLoaderMoreLoaded(result.getData());
                }
            }
        }
    }

    private void handleLoaderMoreError(int categoryId) {
        mCurrentPage--;
        pagesInfo.put(categoryId,mCurrentPage);
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId()==categoryId) {
                callback.onLoaderMoreError();
            }
        }
    }

    @Override
    public void reload(int categoryId) {

    }



    @Override
    public void registerViewCallback(ICategoryPagerCallback callback) {
        if (!callbacks.contains(callback)){
            callbacks.add(callback);
        }
    }

    @Override
    public void unregisterViewCallback(ICategoryPagerCallback callback) {
        callbacks.remove(callback);
    }
}
